#!/bin/bash
set -e

log=.log.`date +%N`
echo `basename $0` $@ >>$log
prog=`basename $0`
args=$@

function info() {
cat /mnt/ilustre/app/medical/tools/script/info.snp.bt.txt
exit 65
}

function error() {
echo `basename $0`': invalid option -?'
info
}


while getopts  ":s:i:l:d:LGnc:Ab:p:m:q:" opts
do
        case  $opts  in
		b) assembly=$OPTARG;;
        i) interval=$OPTARG
			i=i;;
		l) interval=$OPTARG
			f=f;;
		G) somatic=T;;
		d) desti=$OPTARG;;
		n) cutadaptor=$OPTARG
			n=n;;
		c) cnv=$OPTARG
			c=c;;
		m) mem=$OPTARG
			m=m;;
		p) cpu=$OPTARG
			p=p;;
		q) query=$OPTARG
			q=q;;
		A) a=n;;
		s) sample_name=$OPTARG;;
		L) run_local=T;;
		h) info;;
		\?) error;;
        esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then info; fi

if [ -z "$sample_name" ]; then
if test -d $1; then
sample_name=`fq_name.pl $1`;
if test -z $sample_name; then sample_name=test; fi
else sample_name=test
fi
fi

if [ -z "$desti" ]; then desti=snp; fi
if [ -z "$assembly" ]; then assembly=38; fi


if test -z "$run_local"; then 
subq.sh -n$sample_name $prog -L $args


clear
echo A snp calling and annotion job, name $sample_name, submitted to pbs...
exit 0
else
echo A snp calling and annotion job run in local...
fi

if
echo $1 |perl -n -e 'if(/^\//){exit 0;}else{exit 2;}'
then
a=$1
else
a=`pwd`/$1
fi

if test -n "$2"; then


if
echo $2 |perl -n -e 'if(/^\//){exit 0;}else{exit 2;}'
then
b=$2
else
b=`pwd`/$2
fi


r12=`echo $a $b`
elif test -d $1; then
num=`ls -1 $1|wc -l`
	if test $num -eq 2; then
	ab=`ls $a`
	aa=`echo $ab |cut -d' ' -f1`
	bb=`echo $ab |cut -d' ' -f2`
	r12=`echo $a/$aa $a/$bb`
	fi
fi


makedir=true


. /mnt/ilustre/app/medical/tools/.var



if [ -n "$p" ]; then
	qsub_cmd="$qsub_cmd -l nodes=1:ppn=$cpu"
fi

if [ -n "$m" ]; then
	qsub_cmd="$qsub_cmd -l mem=${mem}gb"
fi

if [ -n "$q" ]; then
	qsub_cmd="$qsub_cmd -$q $query"
fi


if [ "$interval" = "brca12ph" ]; then
	cutadp=cutadp_ph_miseq.sh
	target=$data_path/intervals/1/brca12_b37_sort_ph.bed
elif [ "$interval" = "ctc80" ]; then
	cutadp=cutadp_ctc80_discard_trimmed.sh
	target=$data_path/intervals/1/ctc80.bed
elif [ "$interval" = "brca12mor" ]; then
	cutadp=cutadp_ph_miseq.sh
	target=$data_path/intervals/1/brca12_mor.bed
elif [ "$interval" = "ca50mor" ]; then
	cutadp=cutadp_ph_miseq.sh
	target=$data_path/intervals/1/ca50_mor.bed
else
	cutadp=cutadp.sh
	min_len=60
fi

echo $target
echo $cutadp




if test "$cutadp" = "cutadp.sh";then
$cutadp -m$min_len -p$out_prefix $r12
else
$cutadp -p$out_prefix $r12
fi


align_bt_0302.sh -s$sample_name $out_prefix.1.cut.fastq $out_prefix.2.cut.fastq

markdup_0302.sh $out_prefix.sort.bam

realign_bt.sh $out_prefix.markdup.bam
fastqc.sh -s$sample_name $out_prefix.markdup.bam &

bam_q_filter.sh $out_prefix.realn.bam